package com.example.feifei.net.download.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.example.feifei.net.download.bean.FileInfo;
import com.example.feifei.utils.LogUtils;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import retrofit2.http.Url;


/**
 * Created by Administrator on 2018\6\13 0013.
 */

public class DownloadService extends Service{

    private static final String TAG = "DownloadService";

    //初始化
    private static final int MSG_INIT = 0;
    //开始下载
    public static final String ACTION_START = "ACTION_START";
    //暂停下载
    public static final String ACTION_PAUSE = "ACTION_PAUSE";
    //更新UI
    public static final String ACTION_UPDATE = "ACTION_UPDATE";
    //结束下载
    public static final String ACTION_FINISHED = "ACTION_FINISHED";

    //下载路径
    public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads/";

    private DownloadTask mDownloadTask = null;

    /**
     * 开启服务
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(ACTION_START.equals(intent.getAction())){
            FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileinfo");
            new InitThread(fileInfo).start();
        }else if(ACTION_PAUSE.equals(intent.getAction())){
            FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileinfo");
            Log.e(TAG, "onStartCommand:ACTION_PAUSE- " + fileInfo.toString());
            if (mDownloadTask != null) {
                mDownloadTask.isPause = true;
            }
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 初始化子线程
     */
    class InitThread extends Thread{
        private FileInfo fileInfo;

        public InitThread(FileInfo fileInfo) {
            this.fileInfo = fileInfo;
        }

        @Override
        public void run() {
            HttpURLConnection conn = null;//网络请求
            RandomAccessFile raf = null;//随机访问文件
            try {
                URL url = new URL(fileInfo.getUrl());
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3000);
                conn.setRequestMethod("GET");
                int len = -1;
                if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                    len = conn.getContentLength();//获取文件长度
                }
                if(len < 0){
                    return;
                }
                File dir = new File(DOWNLOAD_PATH);
                if(!dir.exists()){
                    dir.mkdir();
                }
                File file = new File(dir,fileInfo.getFileName());
                raf = new RandomAccessFile(file,"rwd");
                raf.setLength(len);//设置本地文件长度
                LogUtils.e("获取到的文件长度===="+len);
                fileInfo.setLength(len);
                mHandler.obtainMessage(MSG_INIT,fileInfo).sendToTarget();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if (conn != null && raf != null) {
                        raf.close();
                        conn.disconnect();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_INIT:
                    FileInfo fileinfo = (FileInfo) msg.obj;
                    Log.e("mHandler--fileinfo:", fileinfo.toString());
                    //启动下载任务
                    mDownloadTask = new DownloadTask(DownloadService.this, fileinfo);
                    mDownloadTask.download();
                    break;
            }
        }
    };
}
